package com.felix.spider.service;

import com.felix.spider.domain.TrainManage;
import com.felix.spider.domain.TrainTime;
import com.felix.spider.rep.TrainManageRep;
import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TrainDataService {

  @Autowired private TrainManageRep trainManageRep;

  @Value("${spider.file.basedir}")
  private String fileDir;

  /** 清除数据库中车次的空格 */
  public void clearData() {
    List<TrainManage> all = trainManageRep.findAll();
    for (TrainManage trainManage : all) {
      String trainNumber = trainManage.getTrainNumber();
      trainManage.setTrainNumber(trainNumber.trim());
      trainManageRep.save(trainManage);
    }
    trainManageRep.findAll();
  }

  /**
   * 写入TXT，追加写入
   *
   * @param filename
   * @param data
   */
  public void fileChaseFW(String filename, String data) {
    try {
      File file = new File(fileDir, filename);
      // 构造函数中的第二个参数true表示以追加形式写文件
      FileWriter fw = new FileWriter(file, true);
      fw.write(data);
      fw.close();
    } catch (IOException e) {
      System.out.println("文件写入失败！" + e);
    }
  }

  /**
   * 通过车次获取数据转成json数据存入文件
   *
   * @param trainNumber
   * @throws IOException
   */
  public void getTrainTime(String trainNumber) throws IOException {
    Gson gson = new Gson();
    ArrayList<TrainTime> trainTimes = new ArrayList<>();
    String url = "http://qq.ip138.com/train/" + trainNumber + ".htm";
    Document document = null;
    try {
      document = Jsoup.connect(url).get();
    } catch (IOException e) {
      fileChaseFW("_error.txt", trainNumber + "\n");
      System.out.println("-----" + trainNumber + "错误！！-----");
      return;
    }
    Elements select = document.select("#stationInfo > center > table > tbody > tr");
    if (select.size() > 2) {
      for (int i = 1; i < select.size(); i++) {
        Element element = select.get(i);
        if (element.children().size() > 6) {
          String sno = element.child(0).text().trim();
          String stationName = element.child(1).text().trim();
          String arrivalTime = element.child(2).text().trim();
          String startTime = element.child(3).text().trim();
          String walkTime = element.child(4).text().trim();
          String mileage = element.child(5).text().trim();
          TrainTime trainTime =
              new TrainTime(
                  sno, trainNumber, stationName, arrivalTime, startTime, walkTime, mileage);
          trainTimes.add(trainTime);
        }
      }
      createFile(trainNumber + ".json", gson.toJson(trainTimes));
      System.out.println("-----" + trainNumber + "以保存-----");
    } else {
      fileChaseFW("_error.txt", trainNumber + "\n");
      System.out.println("-----" + trainNumber + "错误！！-----");
    }
  }

  /**
   * 覆盖存入文件
   *
   * @param name
   * @param data
   */
  public void createFile(String name, String data) {
    try {
      File file = new File(fileDir, name);
      FileOutputStream fileOutputStream = null;
      fileOutputStream = new FileOutputStream(file);
      fileOutputStream.write(data.getBytes("UTF-8"));
      fileOutputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
